<template>
  <div v-loading="loading" class="app-container">
    <el-collapse v-model="activeName" accordion>
      <el-collapse-item name="1">
        <template slot="title">
          <i class="el-icon-search" />搜索栏
        </template>
        <div class="head-container">
          <el-form class="searchform" :model="params" :inline="true" size="mini" label-width="auto">
            <el-row>
              <el-col :span="8">
                <el-form-item label="部门">
                  <el-input v-model="params.deptNbr" size="mini" placeholder="英文半角逗号分隔，多个搜索" clearable style="width: 200px;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="Fineline号">
                  <el-input v-model="params.finelineNbr" size="mini" placeholder="英文半角逗号分隔，多个搜索" clearable style="width: 200px;" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="Fineline名称">
                  <el-input v-model="params.finelineName" size="mini" placeholder="输入搜索" clearable style="width: 200px;" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="绑定状态">
                  <el-select v-model="params.isBinded" placeholder="选择搜索" clearable size="mini" style="width: 200px">
                    <el-option v-for="item in getOptions().bindStatuses" :key="item.key" :label="item.name" :value="item.val" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item>
                  <el-button size="mini" type="primary" style="float:right;margin-left:0px;" round icon="el-icon-refresh" @click="resetForm">重置</el-button>
                  <el-button size="mini" type="primary" style="float:right;margin-left:0px;" round icon="el-icon-search" @click="toQuery">查询</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
    <div style="padding-top: 10px">
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="downloadExcel">导出</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="toBatchEdit">批量操作</el-button>
      <el-button size="mini" type="primary" style="float:right;margin-bottom:5px;margin-left:0px;" round @click="doClearSelection">取消选择</el-button>
      <el-table
        ref="dataTab"
        :data="data"
        :row-key="getRowKeys"
        :expand-row-keys="expandRowKeys"
        stripe
        size="mini"
        border
        style="width: 100%;"
        @row-click="rowClick"
        @selection-change="handleSelectionChange"
        @expand-change="doExpandChange"
      >
        <el-table-column :reserve-selection="true" type="selection" align="center" width="55" />
        <el-table-column :reserve-selection="true" label="展开" type="expand" width="55">
          <template slot-scope="scope">
            <div v-loading="scope.row.loading">
              <el-table :data="scope.row.mappingList" stripe size="mini" border style="width: 100%;">
                <el-table-column label="类目类型" prop="categoryTypeName" />
                <el-table-column label="映射类目" prop="categoryNames" />
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="部门" prop="deptNbr" :width="colWidths.deptNbr" />
        <el-table-column :show-overflow-tooltip="true" label="Fineline号" prop="finelineNbr" :width="colWidths.finelineNbr" />
        <el-table-column :show-overflow-tooltip="true" label="Fineline名称" prop="finelineName" :width="colWidths.finelineName" />
        <el-table-column :show-overflow-tooltip="true" label="绑定状态" prop="mappingStatus" :width="colWidths.mappingStatus">
          <template slot-scope="scope">
            <div v-for="bindStatus in getOptions().bindStatuses" :key="bindStatus.val">
              <span v-if="scope.row.mappingStatus === bindStatus.val">{{ bindStatus.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="更新时间" prop="updateTime" :width="colWidths.updateTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="更新人" prop="updateBy" :width="colWidths.updateBy" />
        <el-table-column label="操作" align="left" fixed="right" width="100">
          <template slot-scope="scope">
            <el-link size="mini" type="primary" style="margin-left:0px;" @click="toBind(scope.row)">
              <span style="font-size: 12px;">操作</span>
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <el-pagination
        :total="total"
        :current-page.sync="currentPage"
        :page-sizes="[10,50,100,500]"
        style="margin-top: 8px;"
        layout="total, prev, pager, next, sizes"
        @size-change="sizeChange"
        @current-change="pageChange"
      />
    </div>
    <finelineCategoryBind ref="finelineCategoryBind" :parent="parent" />
  </div>
</template>

<script>
import initData from '@/api/coi/itemCenterInitData'
import { batchDelete, relieveBind, getCategoryMappingByFinelineNbr } from '@/api/coi/mapping/fineline-category'
import finelineCategoryBind from './fineline-category-edit-bind.vue'
import { getOptions } from '@/views/coi/mapping/js/options'
import { getCategoryDataTreeList, getAllCategoryType } from '@/api/coi/category/category'
import { messageShowTool } from '@/utils/messageUtil'
import { parseTime } from '@/utils/index'
import { doDownload } from '@/api/olm/download'

export default {
  components: { finelineCategoryBind },
  mixins: [initData],
  data() {
    return {
      activeName: '1',
      parent: this,
      ids: [],
      loading: false,
      currentObj: this,
      finelineDataList: [],
      categoryOptions: [],
      categoryTypes: [],
      expandRowKeys: []
    }
  },
  created() {
    this.$nextTick(() => {
      this.loading = true
      this.init()
      getAllCategoryType().then(res => {
        if (res && res.result) {
          this.categoryTypes = res.result
          this.categoryTypes.forEach(obj => {
            obj.multiple = obj.shopCategoryFlag === 1
            getCategoryDataTreeList({ channelId: obj.channelId, shopCategoryFlag: obj.shopCategoryFlag }).then(_res => {
              if (res.result) {
                obj.categoryOptions = _res.result
              }
            }, error => {
              console.log(error)
            })
          })
        } else {
          this.messageShowTool('获取类目类型数据失败。', 'danger')
        }
        this.loading = false
      })
    })
  },
  methods: {
    getOptions,
    messageShowTool,
    parseTime,
    beforeInit() {
      this.url = process.env.VUE_APP_BASE_API6 + '/mapping/finelineCategory/queryPageList'
      this.params.pageNum = this.page
      this.params.pageSize = this.size
      this.params.channelId = null
      this.params.categoryType = null
      if (this.params.categoryInfo) {
        this.params.channelId = this.params.categoryInfo.channelId
        this.params.categoryType = this.params.categoryInfo.key
      }

      return true
    },
    // 查询
    toQuery() {
      this.page = 1
      this.currentPage = 1
      this.params.deptNbrs = null
      this.params.finelineNbrs = null
      if (this.params.deptNbr) {
        this.params.deptNbrs = this.params.deptNbr.split(',')
      }
      if (this.params.finelineNbr) {
        this.params.finelineNbrs = this.params.finelineNbr.split(',')
      }
      this.init()
      this.doClearSelection()
      this.expandRowKeys = []
    },
    // 查询栏重置触发
    resetForm() {
      this.params = {}
      this.syncTime = []
      this.toQuery()
    },
    // 点击行触发
    rowClick(row) {
      this.$refs.dataTab.clearSelection()
      this.$refs.dataTab.toggleRowSelection(row, true)
    },
    // 列表多选框触发
    handleSelectionChange(val) {
      this.ids = []
      val.forEach(_obj => {
        this.ids.push(_obj.id)
      })
      this.finelineDataList = val
    },
    // 翻页选择row的key值
    getRowKeys(row) {
      return row.deptNbr + row.finelineNbr
    },
    // 清空选择项
    doClearSelection() {
      this.ids = []
      this.finelineDataList = []
      this.$refs.dataTab.clearSelection()
    },
    toBind(val) {
      if (val) {
        this.finelineDataList = []
        this.finelineDataList.push(val)
      }
      this.toBatchEdit()
    },
    // 批量绑定
    toBatchEdit() {
      if (this.finelineDataList.length < 1) {
        this.messageShowTool('请选择需要编辑的item。', 'error')
        return
      }
      if (this.finelineDataList.length > 50) {
        this.messageShowTool('单次操作数量上限：50', 'error')
        return
      }
      const finelineCategoryBind = this.$refs.finelineCategoryBind
      finelineCategoryBind.bindPageTitle = 'Fineline-类目映射'
      const categoryTypes = JSON.parse(JSON.stringify(this.categoryTypes))
      if (this.finelineDataList.length === 1) {
        const finelineDataObj = this.finelineDataList[0]
        getCategoryMappingByFinelineNbr({ deptNbr: finelineDataObj.deptNbr, finelineNbr: finelineDataObj.finelineNbr }).then(res => {
          if (res && res.result) {
            const list = res.result
            categoryTypes.forEach(_type => {
              list.forEach(obj => {
                if (_type.categoryType === obj.categoryType) {
                  if (obj.mappings && obj.mappings.length > 0) {
                    if (_type.multiple === false) {
                      _type.categoryData = JSON.parse(obj.mappings[0].categoryTree)
                    } else {
                      const categoryData = []
                      obj.mappings.forEach(mp => {
                        categoryData.push(JSON.parse(mp.categoryTree))
                      })
                      _type.categoryData = categoryData
                    }
                  }
                }
              })
            })
          }
          finelineCategoryBind.$forceUpdate()
        }, error => {
          console.log(error)
        })
      }
      finelineCategoryBind.categoryTypes = categoryTypes
      finelineCategoryBind.dialog = true
    },
    // 解绑
    toBatchRelieveBind(val) {
      this.$confirm('确认解除当前绑定吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        const paramArray = []
        val.mappings.forEach(map => {
          paramArray.push({ deptNbr: val.deptNbr, flCategoryId: map.flCategoryId, finelineNbr: val.finelineNbr, categoryType: val.categoryType })
        })
        relieveBind(paramArray).then(res => {
          this.messageShowTool('操作成功。', 'success')
          this.toQuery()
          this.loading = false
        }, error => {
          console.log(error)
          this.loading = false
        })
      })
    },
    // 删除
    doDelete() {
      if (this.finelineDataList.length < 1) {
        this.messageShowTool('请选择需要编辑的item。', 'error')
        return
      }
      if (this.finelineDataList.length > 50) {
        this.messageShowTool('单次操作数量上限：50', 'error')
        return
      }
      this.$confirm('确认删除选择的 ' + this.finelineDataList.length + ' 条item信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        batchDelete(this.finelineDataList).then(res => {
          this.messageShowTool('操作成功。', 'success')
          this.toQuery()
          this.loading = false
        }, error => {
          console.log(error)
          this.loading = false
        })
      })
    },
    // 展开行
    doExpandChange(row, expandedRows) {
      if (!row.mappingList) {
        this.$set(row, 'loading', true)
        const data = JSON.parse(JSON.stringify(this.categoryTypes))
        getCategoryMappingByFinelineNbr({ deptNbr: row.deptNbr, finelineNbr: row.finelineNbr }).then(res => {
          if (res && res.result) {
            const list = res.result
            data.forEach(_type => {
              list.forEach(obj => {
                if (_type.categoryType === obj.categoryType) {
                  _type.mappings = obj.mappings
                  _type.categoryNames = obj.mappings.map(function(mp, idx) {
                    return mp.categoryName
                  }).join(',')
                }
              })
            })
          }
          this.$set(row, 'mappingList', data)
          this.$set(row, 'loading', false)
        }, error => {
          console.log(error)
          this.$set(row, 'loading', false)
        })
      }
    },
    // 导出
    downloadExcel() {
      this.loading = true
      doDownload(process.env.VUE_APP_BASE_API6 + '/mapping/finelineCategory/exportMappingData', this.params, 'Fineline-类目映射.xlsx').then(_ => {
        this.loading = false
      }, error => {
        console.log(error)
        this.loading = false
      })
    }
  }
}
</script>
